package com.tepth.remote.control.delegate.picture.upload;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.tencent.bugly.crashreport.BuglyLog;
import com.tencent.bugly.crashreport.CrashReport;
import com.tepth.remote.control.R;
import com.tepth.remote.control.R2;
import com.tepth.remote.control.base.bean.Config;
import com.tepth.remote.control.base.bean.Fences;
import com.tepth.remote.control.base.bean.Project;
import com.tepth.remote.control.base.config.ApiDictionary;
import com.tepth.remote.control.base.convert.ObjectConverter;
import com.tepth.remote.control.delegate.BasePermissionCheckerDelegate;
import com.tepth.remote.control.manager.ConfigManager;
import com.tepth.remote.core.app.Control;
import com.tepth.remote.core.net.CommonParams;
import com.tepth.remote.core.net.callback.IError;
import com.tepth.remote.core.net.callback.IFailure;
import com.tepth.remote.core.net.callback.ISoapSuccess;
import com.tepth.remote.core.net.callback.ISuccess;
import com.tepth.remote.core.net.retrofit.RxRetrofitClient;
import com.tepth.remote.core.net.soap.SoapClient;
import com.tepth.remote.core.utils.camera.BitmapUtils;
import com.tepth.remote.core.utils.camera.CommonUtils;
import com.tepth.remote.core.utils.file.FileUtil;
import com.tepth.remote.core.utils.resources.ResourcesUtil;
import com.tepth.remote.ui.alert.DialogLoader;
import com.tepth.remote.ui.alert.IDialogClickListener;
import com.tepth.remote.ui.recycler.MultipleFields;
import com.tepth.remote.ui.recycler.MultipleItemEntity;
import com.tepth.remote.ui.recycler.MultipleRecyclerAdapter;
import com.tepth.remote.ui.recycler.MultipleRecyclerClickListener;
import com.tepth.remote.ui.recycler.grid.GridItemType;

import org.ksoap2.serialization.SoapObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/11/25
 */
@SuppressLint("SetTextI18n")
public class PictureUploadDelegate extends BasePermissionCheckerDelegate implements MultipleRecyclerClickListener {

    @BindView(R2.id.rv_project)
    RecyclerView recyclerView = null;
    @BindView(R2.id.linear_picture_upload_layout)
    LinearLayoutCompat linearUploadLayout = null;
    @BindView(R2.id.text_upload_project_name)
    AppCompatTextView textProjectName = null;
    @BindView(R2.id.text_upload_fence_name)
    AppCompatTextView textFenceName = null;
    @BindView(R2.id.text_upload_time)
    AppCompatTextView textUploadTime = null;
    @BindView(R2.id.linear_picture_upload_operate)
    LinearLayoutCompat linearPictureUploadOperate = null;
    @BindView(R2.id.image_camera)
    AppCompatImageView imageCamera = null;

    private MultipleRecyclerAdapter mAdapter = null;
    private DialogLoader mDialogLoader = null;
    private int lastProjectIndex = -1;
    private String showCalendar = "";
    private Fences selectFences = null;
    private File uploadFile = null;
    private boolean uploading = false;
    /**
     * 启动照相Intent的RequestCode.系统相机.
     */
    public static final int TAKE_PHOTO_SYSTEM = 200;
    private File mFile;
    /**
     * 设置图片加载策略
     */
    private static final RequestOptions REQUEST_OPTIONS = new RequestOptions()
            .centerInside()
            .centerCrop()
            .error(R.drawable.image_error)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .dontAnimate();

    @Override
    public Object setLayout() {
        return R.layout.delegate_picture_upload;
    }

    @OnClick({R2.id.image_camera, R2.id.linear_picture_upload, R2.id.linear_picture_upload_retry, R2.id.button_refresh})
    void onClick(View view) {
        final int id = view.getId();
        if (id == R.id.image_camera) {
            if (uploadFile != null) {
                return;
            }
            if (selectFences == null) {
                ToastUtils.showShort("请先选择围栏");
                return;
            }
            startCamera();
        } else if (id == R.id.linear_picture_upload_retry) {
            startCamera();
        } else if (id == R.id.linear_picture_upload) {
            if (uploadFile == null) {
                ToastUtils.showShort("请先拍照");
                return;
            }
            uploadBitmap();
        } else {
            mDialogLoader.showProgressDialog(false, "正在加载", "");
            RxRetrofitClient.builder()
                    .url(ApiDictionary.API_GET_CONFIG)
                    .params("Imei", ConfigManager.getInstance().getPhoneId())
                    .success(new ISuccess() {
                        @Override
                        public void onSuccess(Object value) {
                            mDialogLoader.clearDialog();
                            final Config config = new ObjectConverter<Config>().convert(JSON.toJSONString(value),
                                    new TypeReference<Config>() {
                                    });
                            ConfigManager.getInstance()
                                    .setRealName(config.getRealName())
                                    .setUid(config.getUid())
                                    .setPhoneId(config.getPhoneId())
                                    .setIsBm(config.getIsBm())
                                    .setIsZj(config.getIsZj())
                                    .setProjects(config.getProjects());
                            final ArrayList<Project> allData = config.getProjects();
                            PictureUploadDataConvert convert = new PictureUploadDataConvert();
                            mAdapter.setNewData(convert.setData(convert.convertProjectToObject(allData)).convert());
                        }
                    })
                    .error(new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            mDialogLoader.clearDialog();
                        }
                    })
                    .builder()
                    .get();
        }
    }

    private void uploadBitmap() {
        if (uploading) {
            return;
        } else {
            uploading = true;
        }
        final MultipleItemEntity entity = mAdapter.getItem(lastProjectIndex);
        if (entity == null) {
            ToastUtils.showShort("请选择项目");
            return;
        }
        final Project project = entity.getField(MultipleFields.PROJECT);
        if (project == null) {
            ToastUtils.showShort("请选择围栏");
            return;
        }
        try {
            mDialogLoader.showProgressDialog(false, "正在上传", "");
            final WeakHashMap<String, Object> params = new WeakHashMap<>();
            params.put("uid", ConfigManager.getInstance().getUid());
            params.put("proId", project.getPro_Id());
            params.put("eleId", selectFences.getEFB_ID());
            params.put("photodate", showCalendar);
            params.put("y", String.valueOf(106.55837396));
            params.put("x", String.valueOf(29.56895320));
            final InputStream isInputStream = new FileInputStream(uploadFile);
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count;
            while ((count = isInputStream.read(buffer)) >= 0) {
                arrayOutputStream.write(buffer, 0, count);
            }
            String uploadBuffer = new String(Base64.encode(arrayOutputStream.toByteArray(),
                    Base64.NO_WRAP));
            params.put("base64String", uploadBuffer);
            SoapClient.builder()
                    .params(params)
                    .methodName(ApiDictionary.API_UPLOAD_PICTURE)
                    .nameSpace(ApiDictionary.SOAP_OLD_NAME_SPACE)
                    .success(new ISoapSuccess() {
                        @Override
                        public void onSuccess(SoapObject object) {
                            uploading = false;
                            final int code = Integer.parseInt(object.getPropertySafelyAsString("Code"));
                            if (code == CommonParams.SUCCESS_CODE_NORMAL) {
                                uploadFile = null;
                                if (imageCamera != null) {
                                    imageCamera.setImageResource(R.drawable.cam_people);
                                }
                                mDialogLoader.stopProgressWithSuccess("上传成功", "", new IDialogClickListener() {
                                    @Override
                                    public void onClick() {
                                        mDialogLoader.clearDialog();
                                    }
                                });
                                if (textUploadTime != null) {
                                    textUploadTime.setText("拍照时间：未拍照，无拍照时间");
                                }
                            } else {
                                mDialogLoader.stopProgressWithFailed("上传失败", "");
                            }
                        }
                    })
                    .error(new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            uploading = false;
                            BuglyLog.e(ApiDictionary.API_UPLOAD_PICTURE, msg);
                            mDialogLoader.stopProgressWithFailed("上传失败", "");
                        }
                    })
                    .builder()
                    .upload();
        } catch (Exception e) {
            BuglyLog.e(ApiDictionary.API_UPLOAD_PICTURE, "图片压缩失败");
            CrashReport.postCatchedException(e);
            uploading = false;
            e.printStackTrace();
            Control.getHandler().post(new Runnable() {
                @Override
                public void run() {
                    mDialogLoader.stopProgressWithFailed("图片压缩失败，请重试", "");
                }
            });
        }
    }

    private void startCamera() {
        try {
            //调用系统相机进行拍照
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            mFile = CommonUtils.createImageFile("mFile");
            Uri uri = FileProvider.getUriForFile(getProxyActivity(), Control.getApplicationContext().getPackageName() + ".FileProvider", mFile);
            List<ResolveInfo> resolvedIntentActivities = Control.getApplicationContext().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolvedIntentInfo : resolvedIntentActivities) {
                String packageName = resolvedIntentInfo.activityInfo.packageName;
                //授予所有能响应ACTION_IMAGE_CAPTURE Intent的App Uri读写权限
                Control.getApplicationContext().grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            //授予自己Uri读写权限
            Control.getApplicationContext().grantUriPermission(Control.getApplicationContext().getPackageName(), uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, TAKE_PHOTO_SYSTEM);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShort("请先授权相机权限");
            startCameraWithCode();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK && resultCode != TAKE_PHOTO_SYSTEM) {
            return;
        }
        if (requestCode == TAKE_PHOTO_SYSTEM) {
            SoapClient.builder()
                    .methodName(ApiDictionary.API_GET_SERVICE_DATE)
                    .nameSpace(ApiDictionary.SOAP_NAME_SPACE)
                    .success(new ISoapSuccess() {
                        @Override
                        public void onSuccess(SoapObject object) {
                            final int code = Integer.parseInt(object.getProperty("Code").toString());
                            if (code == CommonParams.SUCCESS_CODE_ZERO) {
                                showCalendar = object
                                        .getPropertyAsString("Value");
                                if (showCalendar.length() == 0) {
                                    showCalendar = TimeUtils.getNowString();
                                }
                                handlerPicture();
                            }
                        }
                    })
                    .error(new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            showCalendar = TimeUtils.getNowString();
                            handlerPicture();
                        }
                    })
                    .failure(new IFailure() {
                        @Override
                        public void onFailure() {
                            showCalendar = TimeUtils.getNowString();
                            handlerPicture();
                        }
                    })
                    .builder()
                    .post();

        }
    }

    private void handlerPicture() {
        if (mFile == null) {
            ToastUtils.showShort("未找到照片");
            return;
        }
        Luban.with(getProxyActivity())
                .load(mFile)
                .ignoreBy(100)
                .setTargetDir(FileUtil.getDirPath(FileUtil.UPDATE_CACHE_IMAGE))
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        mDialogLoader.showProgressDialog(false, "正在压缩图片", "");
                    }

                    @Override
                    public void onSuccess(File file) {
                        mDialogLoader.clearDialog();
                        if (imageCamera != null) {
                            final Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
                            final Bitmap bit = BitmapUtils.watermark(showCalendar, getProxyActivity());
                            final Bitmap result = BitmapUtils.createBitmap(bitmap, bit);
                            uploadFile = BitmapUtils.writeBitmapToFile(result, System.currentTimeMillis() + ".jpg");
                            Glide.with(getProxyActivity())
                                    .load(uploadFile).apply(REQUEST_OPTIONS)
                                    .into(imageCamera);
                            linearPictureUploadOperate.setVisibility(View.VISIBLE);
                            if (textUploadTime != null) {
                                textUploadTime.setText("拍照时间：" + showCalendar);
                            }
                        } else {
                            ToastUtils.showShort("拍照出错，请重试");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mDialogLoader.stopProgressWithFailed("图片压缩失败，请重试", "");
                        mFile = null;
                        uploadFile = null;
                    }
                })
                .launch();
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mDialogLoader = new DialogLoader(getProxyActivity());
        startCameraWithCode();
        readStorageWithCode();
        initRecyclerView();
    }

    private void initRecyclerView() {
        final ArrayList<Project> allData = ConfigManager.getInstance().getProjects();
        textProjectName.setText("项目名称：" + allData.get(0).getPro_Name());
        textUploadTime.setText("拍照时间：未拍照，无拍照时间");
        final PictureUploadDataConvert converter = new PictureUploadDataConvert();
        mAdapter = MultipleRecyclerAdapter.create(converter.setData(
                converter.convertProjectToObject(allData)).convert(), this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        //3.给GridLayoutManager设置滑动的方向
        linearLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
        //4.为recyclerView设置布局管理器
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(mAdapter);
        //一个一个的滑动（完全ViewPager效果）
        final PagerSnapHelper snapHelper = new PagerSnapHelper();
        //其他都与RecyclerView一样，只需要绑定下就行
        snapHelper.attachToRecyclerView(recyclerView);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 项目数量大于1并且当停止滑动时
                if (mAdapter.getItemCount() > 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (linearUploadLayout != null) {
                        linearUploadLayout.removeAllViews();
                        linearUploadLayout.setVisibility(View.GONE);
                    }
                    if (linearPictureUploadOperate != null) {
                        linearPictureUploadOperate.setVisibility(View.GONE);
                    }
                    selectFences = null;
                    uploadFile = null;
                    if (textUploadTime != null) {
                        textUploadTime.setText("拍照时间：未拍照，无拍照时间");
                    }
                    if (imageCamera != null) {
                        imageCamera.setImageResource(R.drawable.cam_people);
                    }
                    //设置什么布局管理器,就获取什么的布局管理器
                    final LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    if (manager != null) {
                        //获取最后一个完全显示的ItemPosition ,角标值
                        final int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                        final MultipleItemEntity newEntity = mAdapter.getItem(lastVisibleItem);
                        if (newEntity != null) {
                            final String name = newEntity.getField(MultipleFields.TEXT);
                            if (textProjectName != null) {
                                textProjectName.setText(name);
                            }
                        }
                    }
                    if (lastProjectIndex >= 0) {
                        if (textFenceName != null) {
                            textFenceName.setText("现场名称：请选择要操作的围栏");
                        }
                        final MultipleItemEntity entity = mAdapter.getItem(lastProjectIndex);
                        if (entity != null) {
                            entity.setField(MultipleFields.IS_PULL, false);
                            mAdapter.setData(lastProjectIndex, entity);
                        }
                        lastProjectIndex = -1;
                    }
                }
            }
        });
    }

    @Override
    public void onclickListener(MultipleFields type, int position) {
        switch (type) {
            case BACK:
                pop();
                break;
            case PULL:
                linearUploadLayout.removeAllViews();
                final MultipleItemEntity entity = mAdapter.getItem(position);
                if (entity != null) {
                    final boolean isPull = entity.getField(MultipleFields.IS_PULL);
                    if (isPull) {
                        linearUploadLayout.setVisibility(View.GONE);
                        lastProjectIndex = -1;
                        selectFences = null;
                        linearPictureUploadOperate.setVisibility(View.INVISIBLE);
                        imageCamera.setImageResource(R.drawable.cam_people);
                        textUploadTime.setText("拍照时间：未拍照，无拍照时间");
                    } else {
                        lastProjectIndex = position;
                        final Project project = entity.getField(MultipleFields.PROJECT);
                        final ArrayList<Fences> fences = project.getUserElecFences();
                        final int size = fences.size();
                        for (int i = 0; i < size; i++) {
                            linearUploadLayout.addView(getTextView(fences.get(i), i));
                        }
                        if (size > 0) {
                            linearUploadLayout.setVisibility(View.VISIBLE);
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onLoadRecyclerError(String msg) {
        if (mDialogLoader != null) {
            mDialogLoader.showNormalHideCancel("提示", "未获取到围栏信息", new IDialogClickListener() {
                @Override
                public void onClick() {
                    mDialogLoader.clearDialog();
                }
            });
        }
    }

    @Override
    public void onclickViewPagerListener(GridItemType type) {
    }

    private AppCompatTextView getTextView(final Fences fences, final int fencePosition) {
        final AppCompatTextView textView = new AppCompatTextView(getProxyActivity());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(ResourcesUtil.getColorFromResources(getContext(), R.color.text_fences));
        textView.setTextSize(20);
        textView.setSingleLine(true);
        textView.setBackgroundResource(R.drawable.text_fences);
        textView.setText(fences.getEFB_Name());
        textView.setTypeface(Typeface.DEFAULT);
        textView.setPadding(0, 10, 0, 10);
        textView.setLayoutParams(lp);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int size = linearUploadLayout.getChildCount();
                for (int i = 0; i < size; i++) {
                    AppCompatTextView text = (AppCompatTextView) linearUploadLayout.getChildAt(i);
                    text.setTextColor(ResourcesUtil.getColorFromResources(getContext(), R.color.text_fences));
                }
                final AppCompatTextView childView = (AppCompatTextView) linearUploadLayout.getChildAt(fencePosition);
                childView.setTextColor(ResourcesUtil.getColorFromResources(getContext(), R.color.home_color));
                final MultipleItemEntity entity = mAdapter.getItem(lastProjectIndex);
                if (entity != null) {
                    final Project project = entity.getField(MultipleFields.PROJECT);
                    final ArrayList<Fences> fences = project.getUserElecFences();
                    textFenceName.setText("现场名称：" + fences.get(fencePosition).getEFB_Name());
                    selectFences = fences.get(fencePosition);
                    linearPictureUploadOperate.setVisibility(View.INVISIBLE);
                    imageCamera.setImageResource(R.drawable.cam_people);
                }
            }
        });
        return textView;
    }
}
